package com.stars.easyms.schedule.impl;

import com.stars.easyms.schedule.DistributedTaskContext;
import com.stars.easyms.schedule.bean.DbScheduleSubTask;
import com.stars.easyms.schedule.util.MapUtil;
import com.stars.easyms.schedule.util.ApplicationContextHolder;
import org.springframework.context.ApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * 分布式任务上下文
 *
 * @author guoguifang
 */
public class DistributedTaskContextImpl implements DistributedTaskContext {

    private String taskId;

    private String taskName;

    private Integer partitionCount;

    private Integer partitionIndex;

    private Map<String, Object> parameters = new HashMap<>(64);

    public DistributedTaskContextImpl(DbScheduleSubTask executableSubTask) {
        this.taskId = executableSubTask.getTaskId();
        this.taskName = executableSubTask.getTaskName();
        this.partitionCount = executableSubTask.getPartitionCount();
        this.partitionIndex = executableSubTask.getPartitionIndex();
        Map<String, Object> taskParameterMap = MapUtil.parse(executableSubTask.getParameters());
        if (taskParameterMap != null) {
            this.parameters.putAll(taskParameterMap);
        }
    }

    @Override
    public ApplicationContext getApplicationContext() {
        return ApplicationContextHolder.getApplicationContext();
    }

    @Override
    public String getTaskId() {
        return this.taskId;
    }

    @Override
    public String getTaskName() {
        return this.taskName;
    }

    @Override
    public Integer getPartitionCount() {
        return this.partitionCount;
    }

    @Override
    public Integer getPartitionIndex() {
        return this.partitionIndex;
    }

    @Override
    public Object get(String key) {
        return this.parameters.get(key);
    }

    public Map<String, Object> getParameters() {
        return this.parameters;
    }

}
